//
//  DateViewController.m
//  Leo01
//
//  Created by 张旭 on 15/9/18.
//  Copyright (c) 2015年 张旭. All rights reserved.
//

#import "DateViewController.h"
#import "SyncManager.h"
#import "LeoMsg.h"


@interface DateViewController ()

@end

@implementation DateViewController
@synthesize confirmButton;
@synthesize cancelButton;
@synthesize pickerView;
@synthesize motherLabel;
@synthesize motherWindow;
@synthesize selectYear;
@synthesize selectMonth;
@synthesize selectDate;
@synthesize selectDateType;
@synthesize yearArray;
@synthesize monthArray;
@synthesize DateArray;
@synthesize Date28Array;
@synthesize Date29Array;
@synthesize Date30Array;
@synthesize Date31Array;
@synthesize Month12Array;
@synthesize numberFormatter;
@synthesize type;

@synthesize originalBirth;

-(void)viewWillAppear:(BOOL)animated
{
    [self initSelectDate];
    [self initDataArray];
    [self initSelectUI];
    [self initButtonActions];
}
-(void)dealloc
{
    self.motherLabel=NULL;
    self.motherWindow=NULL;
    self.selectYear=NULL;
    self.selectMonth=NULL;
    self.selectDate=NULL;
    self.selectDateType=NULL;
    self.yearArray=NULL;
    self.monthArray=NULL;
    self.DateArray=NULL;
    self.Date28Array=NULL;
    self.Date29Array=NULL;
    self.Date30Array=NULL;
    self.Date31Array=NULL;
    self.numberFormatter=NULL;
    self.originalBirth=NULL;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view setFrame:[UIScreen mainScreen].bounds];
    numberFormatter = [[NSNumberFormatter alloc] init];
    pickerView.dataSource=self;
    pickerView.delegate=self;
    // Do any additional setup after loading the view from its nib.
}
-(void)initSelectDate
{
    int year=0; int month=0; int day=0;
    
    if (originalBirth==NULL||[originalBirth isEqualToString:@"0"]||[originalBirth isEqualToString:@""])
    {
        NSDate *now = [NSDate date];
        NSCalendar *calendar = [NSCalendar currentCalendar];
        NSUInteger unitFlags = NSYearCalendarUnit ;
        NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:now];
        year = (int)[dateComponent year];
        unitFlags = NSMonthCalendarUnit ;
        dateComponent = [calendar components:unitFlags fromDate:now];
        month=(int)[dateComponent month];
        unitFlags = NSCalendarUnitDay ;
        dateComponent = [calendar components:unitFlags fromDate:now];
        day=(int)[dateComponent day];
    }
    else
    {
        NSArray * dataArray = [originalBirth componentsSeparatedByString:@"-"];
        if(dataArray==NULL||[dataArray count]<3)
            return;
        if([dataArray objectAtIndex:0]!=NULL)
            year=[[dataArray objectAtIndex:0] intValue];
        if([dataArray objectAtIndex:1]!=NULL)
            month=[[dataArray objectAtIndex:1] intValue];
        if([dataArray objectAtIndex:2]!=NULL)
            day=[[dataArray objectAtIndex:2] intValue];
        if (year-1940<0){return;}
        if (month-1<0){return;}
        if (day-1<0){return;}
    }
    selectYear=[NSString stringWithFormat:@"%d",year];
    selectMonth=[NSString stringWithFormat:@"%d",month];
    selectDate=[NSString stringWithFormat:@"%d",day];

}
-(void)initSelectUI
{
    [pickerView selectRow:([selectYear intValue]-1940) inComponent:0 animated:NO];
    [pickerView selectRow:([selectMonth intValue]-1) inComponent:1 animated:NO];
    [pickerView selectRow:([selectDate intValue]-1) inComponent:2 animated:NO];
}
-(void)initButtonActions{
    [confirmButton addTarget:self action:@selector(submitAction) forControlEvents:UIControlEventTouchDown];
    [cancelButton addTarget:self action:@selector(cancelAction) forControlEvents:UIControlEventTouchDown];
}

-(void)submitAction
{
    self.motherLabel.text = [NSString stringWithFormat:@"%@-%@-%@", selectYear, selectMonth,selectDate];
    self.motherWindow.hidden=YES;
    if(self.type==1)
    {
        SyncManager *syncManager=[[SyncManager alloc] init];
        if(syncManager==NULL)
            return;
        User *user=[User sharedSingleton];
        if(user==NULL)
            return;
        user.birth=self.motherLabel.text;
        NSString *birth=[NSString stringWithFormat:@"%@ 00:00:00",user.birth];
        NSString *birthStamp=[Tooler strToLocalTime:birth];
        user.birth=birthStamp;
        [syncManager setUserInfo1:^(SyncResult result, NSDictionary *retValue, NSString *description) {
            if(result==SUCESS)
            {
                [LeoMsg showMsg:@"生日修改成功"];
            }
            else
            {
                [Tooler showHttpMsg:result description:description msg:@"设置用户生日失败"];

            }
        }];
    }
}

-(void)cancelAction
{
    self.motherWindow.hidden=YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    if(self.view.window==nil)
    {
        self.view=nil;
    }
}

-(void)initDataArray
{
    yearArray = [[NSMutableArray alloc]initWithCapacity:5];
    monthArray = [[NSMutableArray alloc]initWithCapacity:5];
    DateArray = [[NSMutableArray alloc]initWithCapacity:5];
    Date28Array = [[NSMutableArray alloc]initWithCapacity:5];
    Date29Array = [[NSMutableArray alloc]initWithCapacity:5];
    Date30Array = [[NSMutableArray alloc]initWithCapacity:5];
    Date31Array = [[NSMutableArray alloc]initWithCapacity:5];
    Month12Array = [[NSMutableArray alloc]initWithCapacity:5];
    NSDate *now = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSUInteger unitFlags = NSYearCalendarUnit ;
    NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:now];
    int year = [dateComponent year];
    unitFlags = NSMonthCalendarUnit ;
    dateComponent = [calendar components:unitFlags fromDate:now];
    int month=[dateComponent month];
    //int day=[dateComponent day];
    int initYear=1939;
    int gap=year-initYear;
    for (int i = 1; i <= gap; i++) {
        NSNumber *numWithOutAppend = [NSNumber numberWithInt:i];
        NSNumber *numWithAppend = [NSNumber numberWithInt:i+initYear];
        [yearArray addObject:numWithAppend];
        if (i <= 12) {
            [monthArray addObject:numWithOutAppend];
        }
        if (i <= 28) {
            [Date28Array addObject:numWithOutAppend];
            [Date29Array addObject:numWithOutAppend];
            [Date30Array addObject:numWithOutAppend];
            [Date31Array addObject:numWithOutAppend];
        }
        if (i == 29) {
            [Date29Array addObject:numWithOutAppend];
            [Date30Array addObject:numWithOutAppend];
            [Date31Array addObject:numWithOutAppend];
        }
        if (i == 30) {
            [Date30Array addObject:numWithOutAppend];
            [Date31Array addObject:numWithOutAppend];
        }
        if (i == 31) {
            [Date31Array addObject:numWithOutAppend];
        }
    }
    Month12Array=monthArray;
    if ([selectYear isEqualToString:[NSString stringWithFormat:@"%d",year]]){
        [self monthArrayUntilToday];
        if([selectMonth isEqualToString:[NSString stringWithFormat:@"%d",month]])
        {
            [self dateArrayUntilToday];
            return;
        }
    }

    if([self howManyDaysInThisMonth:[selectYear intValue] month:[selectMonth intValue]] == 28){
        selectDateType = @"28";
        DateArray = Date28Array;
    }
    else if([self howManyDaysInThisMonth:[selectYear intValue] month:[selectMonth intValue]] == 29){
        selectDateType = @"29";
        DateArray = Date29Array;
    }
    else if([self howManyDaysInThisMonth:[selectYear intValue] month:[selectMonth intValue]] == 30){
        selectDateType = @"30";
        DateArray = Date30Array;
    }
    else if([self howManyDaysInThisMonth:[selectYear intValue] month:[selectMonth intValue]] == 31){
        selectDateType = @"31";
        DateArray = Date31Array;
    }

}

-(int)howManyDaysInThisMonth:(int)year month:(int)imonth {
    
    if((imonth == 1)||(imonth == 3)||(imonth == 5)||(imonth == 7)||(imonth == 8)||(imonth == 10)||(imonth == 12))
        return 31;
    if((imonth == 4)||(imonth == 6)||(imonth == 9)||(imonth == 11))
        return 30;
    if((year%4 == 1)||(year%4 == 2)||(year%4 == 3))
    {
        return 28;
    }
    if(year%400 == 0)
        return 29;
    if(year%100 == 0)
        return 28;
    return 29;
}

-(void)monthArrayUntilToday
{
    NSDate *now = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSUInteger unitFlags = NSMonthCalendarUnit ;
    NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:now];
    int month=[dateComponent month];
    NSMutableArray *nowMonthArray=[[NSMutableArray alloc]init];
    for (int i=1;i<=month;i++){
        NSNumber *numWithOutAppend = [NSNumber numberWithInt:i];
        [nowMonthArray addObject:numWithOutAppend];
    }
    monthArray=nowMonthArray;

}
-(void)dateArrayUntilToday
{
    NSDate *now = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSUInteger unitFlags = NSDayCalendarUnit ;
    NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:now];
    int day=[dateComponent day];
    NSMutableArray *nowDayArray=[[NSMutableArray alloc]init];
    for (int i=1;i<=day;i++){
        NSNumber *numWithOutAppend = [NSNumber numberWithInt:i];
        [nowDayArray addObject:numWithOutAppend];
    }
    DateArray=nowDayArray;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
//返回显示的列数
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 3;
}
//返回当前列显示的行数
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if (component == 0) {
        return yearArray.count;
    }
    else if (component == 1){
        return monthArray.count;
    }
    else if (component == 2){
        return DateArray.count;
    }
    return DateArray.count;
    
}

//返回当前行的内容,此处是将数组中数值添加到滚动的那个显示栏上
-(NSString*)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if (component == 0) {
        return [numberFormatter stringFromNumber:[yearArray objectAtIndex:row]];
    }
    else if(component == 1){
        return [numberFormatter stringFromNumber:[monthArray objectAtIndex:row]];
    }
    else{
        return [numberFormatter stringFromNumber:[DateArray objectAtIndex:row]];
    }
    
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    NSDate *now = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSUInteger unitFlags = NSYearCalendarUnit ;
    NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:now];
    int year = [dateComponent year];
    unitFlags = NSMonthCalendarUnit ;
    dateComponent = [calendar components:unitFlags fromDate:now];
    int month=[dateComponent month];
    if (component == 0) {
        selectYear = [numberFormatter stringFromNumber:[yearArray objectAtIndex:row]];
        if ([selectYear isEqualToString:[NSString stringWithFormat:@"%d",year]]){
            [self monthArrayUntilToday];
            if([selectMonth isEqualToString:[NSString stringWithFormat:@"%d",month]])
            {
                [self dateArrayUntilToday];
                [pickerView reloadComponent:1];
                [pickerView reloadComponent:2];
                return;
            }

        }else{
            monthArray=Month12Array;
        }
    }
    if (component == 1) {
        selectMonth = [numberFormatter stringFromNumber:[monthArray objectAtIndex:row]];
        if([selectYear isEqualToString:[NSString stringWithFormat:@"%d",year]]&&[selectMonth isEqualToString:[NSString stringWithFormat:@"%d",month]])
        {
            [self dateArrayUntilToday];
            [pickerView reloadComponent:1];
            [pickerView reloadComponent:2];
            return;
        }
    }
    if (component == 2) {
        selectDate = [numberFormatter stringFromNumber:[DateArray objectAtIndex:row]];
        return;
    }
    if([self howManyDaysInThisMonth:[selectYear intValue] month:[selectMonth intValue]] == 28){
        selectDateType = @"28";
        DateArray = Date28Array;
    }
    else if([self howManyDaysInThisMonth:[selectYear intValue] month:[selectMonth intValue]] == 29){
        selectDateType = @"29";
        DateArray = Date29Array;
    }
    else if([self howManyDaysInThisMonth:[selectYear intValue] month:[selectMonth intValue]] == 30){
        selectDateType = @"30";
        DateArray = Date30Array;
    }
    else if([self howManyDaysInThisMonth:[selectYear intValue] month:[selectMonth intValue]] == 31){
        selectDateType = @"31";
        DateArray = Date31Array;
    }
    [pickerView reloadComponent:1];
    [pickerView reloadComponent:2];
}

//Overide view of each component
//-(UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{
//    UILabel* pickerLabel = (UILabel*)view;
//    if (component == 2) {
//        if ([select isEqualToString:@"00"]) {
//            pickerLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 10, 100, 40)];
//            [pickerLabel setTextColor:[UIColor grayColor]];
//            pickerLabel.text=[self pickerView:pickerView titleForRow:row forComponent:component];
//            return pickerLabel;
//        }
//    }
//    pickerLabel = [[UILabel alloc]initWithFrame:CGRectMake(40, 40, 100, 40)];
//    pickerLabel.layoutMargins
//    [pickerLabel setTextColor:[UIColor blackColor]];
//    pickerLabel.text=[self pickerView:pickerView titleForRow:row forComponent:component];;
//    return pickerLabel;
//}


@end
